class NLocalStorage {
  /**
   * @param name localStore的item name值
   * @param type localStore值得类型 String, Array,Object
   * */
  constructor (name, type = 'Array') {
    this.name = name;
    this.type = type;
    let item = JSON.parse(localStorage.getItem(name));
    if (type === 'Array' && item === null ){
      this.item = [];
      return;
    }
    if (type === 'String' && item === null) {
      this.item = '';
      return;
    }
    if (type === 'Object' && item === null) {
      this.item = null;
      return;
    }
    this.item = item;
  }
  setItem (val) {
    if (this.type === 'Array'){
      this.item.unshift(val);
    } else {
      this.item = val;
    }
    this.__localSet();
  }
  editItem (val){
    this.item = val;
    this.__localSet();
  }
  getItem () {
    if(this.type === 'Array' && !this.item.length) return [];
    if(this.type === 'String' && this.item === '') return '';
    if(this.type === 'Object' && this.item === null) return null;
    return JSON.parse(localStorage.getItem(this.name));
  }
  clearItem () {
    if (this.type === 'Array') this.item = [];
    if (this.type === 'String') this.item = '';
    if(this.type === 'Object') this.item = null;
    this.__localSet();
  }
  __localSet() {
    localStorage.setItem(this.name, JSON.stringify(this.item));
  }
}

export default function nLocalStorage(name, type = 'Array') {
  return new NLocalStorage(name, type);
}